<template>
    <ul v-if="totalPage > 0" class="pagination">
        <li :class="currentPage === 1 ? 'disabled' : ''"><a class="cursor-pointer" @click="prev">&laquo;</a></li>
        <li v-for="list in pageList" :key="list.id"
            :class="list === currentPage ? 'active ' : ' ' + list <= 0 ? 'disabled' : '' ">
            <a class="cursor-pointer" @click.prevent.stop="jump" :data-page="list">{{list <= 0 ? '...' : list}}</a>
        </li>
        <li :class="currentPage === totalPage ? 'disabled' : ''"><a class="cursor-pointer" @click="next">&raquo;</a></li>
    </ul>
</template>

<script>
    /* eslint-disable no-undef */

    export default {
        name: 'Pagination',
        data () {
            return {
                pageList: []
            };
        },
        props: {
            totalPage: {type: Number},
            currentPage: {type: Number},
            toPagination: {type: Function}
        },
        watch: {
            currentPage (newValue) {
                this.pagination(newValue);
            },
            totalPage (val) {
                this.pagination(this.currentPage);
            }
        },
        methods: {
            pagination (page) {
                this.pageList = [];
                for (let i = 1; i <= this.totalPage; i++) {
                    if (this.totalPage <= 10) {
                        this.pageList.push(i);
                    } else {
                        if (i <= 3 || i >= this.totalPage - 2) {
                            if ((i === 3 && page > 5) || (i === this.totalPage - 2 && page < this.totalPage - 4)) {
                                this.pageList.push(0);
                            } else {
                                this.pageList.push(i);
                            }
                        } else if (page < 5 && i < 9) {
                            this.pageList.push(i);
                        } else if (page > this.totalPage - 4 && i > this.totalPage - 8) {
                            this.pageList.push(i);
                        } else if (i >= page - 3 && i <= page + 3) {
                            this.pageList.push(i);
                        }
                    }
                }
            },
            jump (e) {
                let em = $(e.srcElement);
                let page = em.attr('data-page');
                if (!em.parent().hasClass('disabled')) {
                    this.toPagination(parseInt(page));
                }
            },
            next (e) {
                if (!$(e.srcElement).parent().hasClass('disabled')) {
                    this.toPagination(parseInt(this.currentPage + 1));
                }
            },
            prev (e) {
                if (!$(e.srcElement).parent().hasClass('disabled')) {
                    this.toPagination(parseInt(this.currentPage - 1));
                }
            }
        },
        mounted () {
            this.pagination(this.currentPage);
        }
    };
</script>
